package com.example.learnvideo.ui

import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.example.learnvideo.R
import com.example.learnvideo.base.BaseActivity
import com.example.learnvideo.databinding.ActivityExoPlayerBinding
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.source.MergingMediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.source.SingleSampleMediaSource
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory
import com.google.android.exoplayer2.util.MimeTypes
import com.google.android.exoplayer2.util.Util
import java.util.*

class ExoPlayerActivity : BaseActivity<ActivityExoPlayerBinding>() {

    companion object{
        const val TAG = "ExoPlayerActivity"
        const val URL_HTTPS = "https://storage.googleapis.com/exoplayer-test-media-0/BigBuckBunny_320x180.mp4"
        const val URL_VIDEO = "http://82.157.163.217/海洋世界.mp4"
        const val URL_SUBTITLE = "http://82.157.163.217/海洋世界.srt"
    }
    // 只在视频库挑选图片的请求码
    private var chooseCode = 3
    private lateinit var mPlayer:SimpleExoPlayer
    // 当前的播放位置
    private var mCurrentPosition = 0L

    private val welcomeArray = arrayOf("首届（2018年）", "第二届（2019年）", "第三届（2020年）", "第四届（2021年）")
    private val urlArray = arrayOf(
        "https://ptgl.fujian.gov.cn:8088/masvod/public/2018/04/17/20180417_162d3639356_r38_1200k.mp4",
        "https://ptgl.fujian.gov.cn:8088/masvod/public/2019/04/15/20190415_16a1ef11c24_r38_1200k.mp4",
        "https://ptgl.fujian.gov.cn:8088/masvod/public/2020/09/26/20200926_174c8f9e4b6_r38_1200k.mp4",
        "https://ptgl.fujian.gov.cn:8088/masvod/public/2021/03/19/20210319_178498bcae9_r38.mp4",
    )

    override fun ActivityExoPlayerBinding.initBinding() {
        //播放本地视频按钮逻辑
        btnPlayLocal.setOnClickListener {
            // ACTION_GET_CONTENT只可选择近期的视频
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            // ACTION_PICK可选择所有视频
            //Intent intent = new Intent(Intent.ACTION_PICK);
            // 类型为视频
            intent.type = "video/*"
            // 打开系统视频库
            startActivityForResult(intent,chooseCode)
        }
        //播放网络视频按钮逻辑
        btnPlayNetwork.setOnClickListener{
            playVideo(Uri.parse("android.resource://${packageName}/${R.raw.test}"))
        }

        //播放带字幕的视频按钮逻辑
        btnPlaySubtitle.setOnClickListener {
            val uri = Uri.parse(URL_VIDEO)
            val subtitleUri = Uri.parse(URL_SUBTITLE)
            playVideoWithSubtitle(uri,subtitleUri)
        }
        mPlayer = SimpleExoPlayer.Builder(this@ExoPlayerActivity).build()
        // 设置播放器视图的播放器对象
        pvContent.player = mPlayer
        // 初始化迎宾曲下拉框
        initWelcomeSpinner()
    }

    // 初始化迎宾曲下拉框
    private fun initWelcomeSpinner(){
        val welcomeAdapter = ArrayAdapter<String>(this,R.layout.item_select,welcomeArray)
        mBinding.spWelcome.prompt = "请选择要播放的迎宾曲"
        mBinding.spWelcome.adapter = welcomeAdapter
        mBinding.spWelcome.onItemSelectedListener = WelcomeSelectedListener()
        mBinding.spWelcome.setSelection(3)
    }

    // 播放视频
    private fun playVideo(uri:Uri){
        // 创建指定视频格式的工厂对象
        val factory:DataSource.Factory = if (uri.toString().startsWith("http")){ // HTTP在线视频
            DefaultHttpDataSource.Factory()
                .setUserAgent(Util.getUserAgent(this,getString(R.string.app_name)))
        } else { // 本地存储卡视频
            DefaultDataSourceFactory(this)
        }
        // 创建指定地址的媒体对象
        val videoItem = MediaItem.Builder().setUri(uri).build()
        // 基于工厂对象和媒体对象创建媒体来源
        val mediaSource = ProgressiveMediaSource.Factory(factory)
            .createMediaSource(videoItem)
        // 设置播放器的媒体来源
        mPlayer.setMediaSource(mediaSource)
        // 给播放器添加事件监听器
        mPlayer.addListener(object :Player.Listener{
            override fun onPlaybackStateChanged(state: Int) {
                when(state){
                    Player.STATE_BUFFERING -> android.util.Log.d(TAG,"视频正在缓冲")
                    Player.STATE_READY -> android.util.Log.d(TAG,"视频准备就绪")
                    Player.STATE_ENDED -> android.util.Log.d(TAG,"视频播放完毕")
                }
            }
        })
        mPlayer.prepare()
        mPlayer.play()
    }

    // 播放带字幕的视频
    private fun playVideoWithSubtitle(uir:Uri,subtitleUri:Uri){
        android.util.Log.d(TAG,"getLanguage = ${Locale.getDefault().language}")
        // 创建指定视频格式的工厂对象
        val factory:DataSource.Factory = DefaultHttpDataSource.Factory()
            .setUserAgent(Util.getUserAgent(this,getString(R.string.app_name)))
        // 创建指定地址的媒体对象
        val mediaItem = MediaItem.Builder().setUri(uir).build()
        // 基于工厂对象和媒体对象创建媒体来源
        val mediaSource = ProgressiveMediaSource.Factory(factory)
            .createMediaSource(mediaItem)
        // 语言要填null，否则中文会乱码。selectionFlags要填Format.NO_VALUE，否则看不到字幕
        // 创建指定地址的字幕对象。ExoPlayer只支持srt字幕，不支持ass字幕
        val subtitleItem = MediaItem.Subtitle(subtitleUri,MimeTypes.APPLICATION_SUBRIP,null,Format.NO_VALUE)
        // 基于工厂对象和字幕对象创建字幕来源
        val subtitleSource = SingleSampleMediaSource.Factory(factory)
            .createMediaSource(subtitleItem, C.TIME_UNSET)
        // 合并媒体来源与字幕来源
        val mergingMediaSource = MergingMediaSource(mediaSource,subtitleSource)
        // 设置播放器的媒体来源
        mPlayer.setMediaSource(mergingMediaSource)
        mPlayer.prepare()
        mPlayer.play()
    }

    override fun onPause() {
        super.onPause()
        // 暂停页面时保存当前的播放进度
        if (mPlayer.isPlaying){
            //获得播放器当前的播放位置
            mCurrentPosition = mPlayer.currentPosition
            //播放器暂停播放
            mPlayer.pause()
        }
    }

    override fun onResume() {
        super.onResume()
        // 恢复页面时立即从上次断点开始播放视频
        if (mCurrentPosition > 0 && !mPlayer.isPlaying){
            //找到指定位置
            mPlayer.seekTo(mCurrentPosition)
        }
        mPlayer.play()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPlayer.release()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == chooseCode){
            if(intent.data != null){
                // 播放视频
                playVideo(intent.data!!)
            }
        }
    }

    private inner class WelcomeSelectedListener:AdapterView.OnItemSelectedListener{

        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            playVideo(Uri.parse(urlArray[position]))
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {
        }

    }
}